package services

import (
	"encoding/json"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/db/mysql/models/models_guess"
	"longmen/server/pkg/db/redis/cache"
	"time"

	_const "longmen/server/pkg/common/helper/const"
)

func GetQuessList() ([]*api_models.GuessInfo, error) {
	// 查出所有
	var ret []*api_models.GuessInfo
	var res []models_guess.Guess
	err := global.Guess().Model(&models_guess.Guess{}).Where("status=1").Scan(&res).Error
	if err != nil {
		return nil, fmt.Errorf("GetQuessList DB Query ERROR:%s", err.Error())
	}

	for _, v := range res {
		key := fmt.Sprintf(_const.GUESS_INFO_REDIS_KEY, v.Id)

		oInfo := &api_models.GuessInfo{}

		sInfo, errRedis := global.GetRds().Get(key).Result()
		if errRedis == nil {
			err = json.Unmarshal([]byte(sInfo), &oInfo) //在里面取信息
			if err != nil {
				return nil, fmt.Errorf("GetQuessList DB Query ERROR:%s", err.Error())
			}

			anchor, _ := cache.GetUserFullInfo(v.AnchorId)
			oInfo.Anchor = anchor.NickName
			oInfo.Avatar = anchor.Avatar

			ret = append(ret, oInfo)
		}
	}

	return ret, nil
}

func GetQuestListByAnchor(anchorID int) ([]models_guess.Guess, error) {
	key := fmt.Sprintf("GUESS_LIST_%d", anchorID)
	var res []models_guess.Guess

	cache.GetCachedData(key, &res)
	if res != nil {
		return res, nil
	}
	if len(res) == 0 {
		err := global.Guess().Model(&models_guess.Guess{}).Where("anchor_id=?", anchorID).Order("create_time desc").Limit(10).Scan(&res).Error
		if err != nil {
			return nil, fmt.Errorf("GetQuestListByAnchor DB Query ERROR:%s", err.Error())
		}
		cache.SetCacheData(key, res, 60*time.Second)
	}

	return res, nil
}
